<?php

namespace addons\qingdong\controller;
use addons\qingdong\model\AdminConfig;
use addons\qingdong\model\FormField;
use app\common\library\Upload;
use app\common\exception\UploadException;
use app\common\model\Area;
use addons\qingdong\model\Field;
use addons\qingdong\model\Form;
use app\common\model\Version;
use think\Config;
use think\Hook;

/**
 *  * 操作文档：https://doc.fastadmin.net/qingdong
 * 软件介绍：https://www.fastadmin.net/store/qingdong.html
 * 售后微信：qingdong_crm
 * 公共接口
 */
class Common extends StaffApi {
	protected $noNeedLogin = ['init','getConfig'];
	protected $noNeedRight = '*';


	/**
	 * 加载初始化
	 * @param string $version 版本号
	 * @param string $lng 经度
	 * @param string $lat 纬度
	 */
	public function init() {
		if ($version = $this->request->request('version')) {
			$lng = $this->request->request('lng');
			$lat = $this->request->request('lat');

			//配置信息
			$upload = Config::get('upload');
			//如果非服务端中转模式需要修改为中转
			if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
				//临时修改上传模式为服务端中转
				set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

				$upload = \app\common\model\Config::upload();
				// 上传信息配置后
				Hook::listen("upload_config_init", $upload);

				$upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
			}

			$upload['cdnurl']    = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
			$upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

			$content = [
				'citydata'    => Area::getCityFromLngLat($lng, $lat),
				'versiondata' => Version::check($version),
				'uploaddata'  => $upload,
				'coverdata'   => Config::get("cover"),
			];
			$this->success('', $content);
		} else {
			$this->error(__('Invalid parameters'));
		}
	}


	/**
	 * 上传文件
	 * @ApiMethod (POST)
	 * @param File $file 文件流
	 */
	public function upload() {

		$attachment = null;
		//默认普通上传文件
		$file = $this->request->file('file');
		$name = input('name','');
        try {
            $upload     = new Upload($file);
            $attachment = $upload->upload();
            $info = $attachment->toArray();
            $file = new \addons\qingdong\model\File();
            $params = [
                'name'          =>  $name ? $name :$info['filename'],
                'save_name'     =>  $info['url'],
                'size'          =>  isset($info['filesize']) ? $info['filesize'] : 0,
                'types'         =>  $info['mimetype'],
                'file_path'     =>  $info['url'],
                'create_staff_id'     =>  empty($staff)?0:$staff->id,
            ];
            $file->data(array_filter($params));
            $file->save();
            $fileId = $file->id;

        } catch (UploadException $e) {
            return json_encode(['code' => 0, 'msg' => $e->getMessage()]);
        }
        $this->success(__('Uploaded successful'), [
            'id'  => $fileId,
            'flie_url' => $params['file_path'],
            'url' => cdnurl($params['file_path'], true)
        ]);
	}


	//select 字段表
	public function selectOption() {

		$fields = Field::where([])->select();
		$data   = [];
		foreach ($fields as $v) {
			$data[$v['name']] = json_decode($v['data'],true);
		}

		$this->success('请求成功', $data);
	}


	//获取form表单
	public function getForm() {
		$type = input('type', 'leads');//leads 线索 customer 客户 contacts 联系人 contract 合同 examine回款 product产品
		$form = Form::where(['type' => $type])->find();

		$this->success('请求成功', json_decode($form['data'], true));
	}


	//获取员工
	public function getSelectStaff() {
		$name  = input('name');
		$where = ['status' => 1];
		if ($name) {
			$where['name'] = ['like', "%{$name}%"];
		}

		$staffs = \addons\qingdong\model\Staff::where($where)->with(['department'])->field('id,name,department_id,nickname,post,img')->select();

		$this->success('请求成功', $staffs);
	}

    /**
     * 获取后台配置
     */
    public function getConfig(){
        $config=get_addon_config('qingdong');
        $data=[
            'map_key'=>AdminConfig::getConfigValue('map_key','wechat'),
            'appid'=>AdminConfig::getConfigValue('appid','wechat'),
            'mobile_name'=>$config['mobile_name']??'CRM'
        ];
        $this->success('请求成功',$data);
    }

    /**
     * 获取时间
     */
    public function getTimes()
    {
        $times = input('times');
        $times = setTimes($times, 'date');
        $this->success('请求成功', ['times' => $times]);
    }

    /**
     * 获取搜索字段
     */
    public function getSearchFields(){
        $type=input('type');//leads
        $fields=FormField::where(['types'=>$type,'field'=>['like',"main_%"],'list_show'=>1,'info_type'=>'main'])->select();
        $this->success('请求成功',$fields);
    }
}
